<template>
	<!-- 代办事项 -->
  <view >
    <view class="search">
      <uni-search-bar
        placeholder="搜索"
        v-model.trim="tabList[Number(current)].searchParams.searchValue"
        cancelText=" "
        class="search-box"
      >
      </uni-search-bar>

      <text @click="search">搜索</text>
    </view>
    <z-tabs
      ref="tabs"
      slot="top"
      class="tab"
      :list="tabList"
      :current="current"
      @change="tabChange"
    ></z-tabs>
    <swiper
      style="height: calc(100vh - 100px)"
      :current="current"
      @transition="swiperTransition"
      @animationfinish="swiperAnimationfinish"
    >
      <swiper-item v-for="(i, j) in tabList" :key="j">
        <scroll-view
          show-scrollbar
          style="height: 100%"
          :scroll-y="true"
          :refresher-enabled="true"
          @refresherrefresh="refresherrefresh"
          :scroll-into-view="intoindex"
          lower-threshold="105"
          @scrolltolower="scrolltolower"
          :refresher-triggered="triggered"
        >
          <view
            class="list-item"
            :id="index === 0 ? `t${current}` : ` `"
            v-for="(item, index) in i.data"
            @click="toDetail(item, current == '0' ? 1 : undefined)"
            v-if="i.data?.length"
            :key="index"
          >
            <view class="item">
              <view class="item-title"> 单据编号：{{ item.billNo }} </view>

              <view class="detail">
                <text>
                  <text class="font-bold">单据类型：</text>
                  {{ item.billTypeName }}
                </text>
                <view v-if="item.value == '1'">
                  <text class="font-bold"> 状态： </text>
                  {{ item.processApprovalStatusName }}
                </view>
                <view v-else
                  ><text class="font-bold"> 状态： </text>
                  {{ item.processApprovalStatusName }}</view
                >
                <view v-if="current != '2'">
                  <text class="font-bold"> 事由： </text>
                  {{ item.taskName }}</view
                >
                <view>
                  <text class="font-bold"> 申请人： </text>
                  {{ item.applicantName }}</view
                >
                <view>
                  <text class="font-bold"> 申请时间： </text>
                  {{ item.applicationTime }}</view
                >
              </view>
            </view>
          </view>
          <view v-else class="no-data"> 暂无数据 </view>
        </scroll-view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script>
import _ from "lodash";
import {
  noticeTotalNumber,
  postActivitiesCompletedTaskList,
  postActivitiesPendingTaskList,
  postActivitiesProcessTaskList,
} from "./api";
import { useAuthStore } from "@/store/modules/auth";
import { mapStores, mapState } from "pinia";
import { useRequest } from "v3hooks";
import { jumpLogin } from "@/utils/routerInterceptor";
import Storage from "@/utils/storageCache";
import { Toast } from "@/utils/uniHooks/toast";
export default {
  data() {
    return {
      intoindex: "t0",
      tabList: [
        {
          value: "0",
          name: "待审核",
          badge: {
            count: useAuthStore().notice?.pendingTaskQty,
          },
          data: [],
          totalCount: 0,
          searchParams: {
            pageNo: 1,
            searchValue: "",
          },
        },
        {
          value: "1",
          name: "已审核",
          data: [],
          totalCount: 0,

          searchParams: {
            pageNo: 1,
            searchValue: "",
          },
        },
        {
          value: "2",
          name: "我的申请",
          data: [],
          totalCount: 0,

          searchParams: {
            pageNo: 1,
            searchValue: "",
          },
        },
      ],
      current: "0", // tabs组件的current值，表示当前活动的tab选项
      triggered: true, //下拉刷新标志
      initFlag: false,
      pageSize: 10,
      refresh: false,
      isFromDetail: false, //判断是否从详情过来
    };
  },

  onShow() {
	  //  监听通知数 此订阅将在组件卸载后保留
	  useAuthStore().$subscribe(
	    (mutation, state) => {
	      this.tabList[0].badge.count = state.notice?.pendingTaskQty;
	    },
	    {
	      detached: true,
	    }
	  );
    this.initFlag = true;
    if (!(this.tabList[0].data.length && !this.isFromDetail)) {
      this.refresherrefresh(); //只有没数据的时候才请求
      this.scroll(false, this.current == "0");
    }
  },


  methods: {
    // changeIsFromDetail(v){
    // 	this.isFromDetail=v
    // },
    scroll(isSearch, isCurrent0Init) {
      if (isSearch || isCurrent0Init) {
        this.$nextTick(() => {
          this.intoindex = `t${this.current}`;
        });
        this.intoindex = ""; //不清空再次跳到锚点位置会不起作用
      }
    },
    search() {
      this.tabList[Number(this.current)].searchParams.pageNo = 1;
      this.triggered = true;
      this.queryList();
      this.scroll(true);
    },
    //swiper滑动中
    swiperTransition(e) {
      this.$refs.tabs.setDx(e.detail.dx);
    },
    //swiper滑动结束
    swiperAnimationfinish(e) {
      this.current = e.detail.current;
      this.$refs.tabs.unlockDx();
    },

    queryList: _.throttle(
      async function () {
        const params = {
          pageSize: this.pageSize,
          wd: this.tabList[Number(this.current)].searchParams.searchValue,
        };
        const getDataCurrent0 = async () => {
          this.tabList[Number(this.current)].searchParams.pageNo = 1;
          const tempData0 = (
            await postActivitiesPendingTaskList({
              ...params,
              pageNo: 1,
            })
          )?.data;
          // console.log(tempData0.abort());
          this.tabList[0].data = tempData0?.rows || [];
          this.tabList[0].totalCount = tempData0?.totalCount || 0;
        };

        if (this.isFromDetail) {
          //如果从详情来就刷新第一个数据

          return getDataCurrent0().finally(() => {
            uni.hideLoading();
            this.triggered = false;
            this.isFromDetail = false;
          });
        } else if (this.initFlag) {
          getDataCurrent0();

          const tempData1 = (
            await postActivitiesCompletedTaskList({
              ...params,
              pageNo: 1,
            })
          )?.data;
          this.tabList[1].data = tempData1?.rows || [];
          this.tabList[1].totalCount = tempData1?.totalCount || 0;
          const tempData2 = (
            await postActivitiesProcessTaskList({
              ...params,
              pageNo: 1,
            })
          )?.data;
          this.tabList[2].data = tempData2?.rows || [];
          this.tabList[2].totalCount = tempData2?.totalCount || 0;

          this.initFlag = false;
        } else {
          if (this.current == "0") {
            const tempData = (
              await postActivitiesPendingTaskList({
                ...params,
                pageNo: this.triggered
                  ? 1
                  : this.tabList[0].searchParams.pageNo + 1,
              })
            )?.data?.rows;

            this.tabList[0].data = this.triggered
              ? tempData
              : [...this.tabList[0].data, ...tempData];
          }
          if (this.current == "1") {
            const tempData = (
              await postActivitiesCompletedTaskList({
                ...params,
                pageNo: this.triggered
                  ? 1
                  : this.tabList[1].searchParams.pageNo + 1,
              })
            )?.data?.rows;

            this.tabList[1].data = this.triggered
              ? tempData
              : [...this.tabList[1].data, ...tempData];
          }
          if (this.current == "2") {
            const tempData = (
              await postActivitiesProcessTaskList({
                ...params,
                pageNo: this.triggered
                  ? 1
                  : this.tabList[2].searchParams.pageNo + 1,
              })
            )?.data?.rows;

            this.tabList[2].data = this.triggered
              ? tempData
              : [...this.tabList[2].data, ...tempData];
          }
          this.tabList[Number(this.current)].searchParams.pageNo++;
          if (this.triggered) {
            this.tabList[Number(this.current)].searchParams.pageNo = 1;
          }
        }
        this.triggered = false;

      },
      500,
      {
        trailing: false,
      }
    ),
    tabChange(i) {
      this.current = String(i);
	  if(i=='1'){
		  this.refresherrefresh(); //只有当是已审核数据的时候才刷新
	  }
    },
    scrolltolower() {
      if (
        this.tabList[Number(this.current)].totalCount >
        this.tabList[Number(this.current)].data.length
      ) {
      uni.showLoading();

        this.queryList();
      }else{
        Toast('暂无更多数据')
      }
    },
    refresherrefresh() {
      this.triggered = true;
      this.queryList();
    },
    toDetail(item, isApproval) {
      uni.navigateTo({
        url: `/pages/todoList/detail?billId=${item.billId}&billType=${item.billType}&isApproval=${isApproval}&billTypeName=${item.billTypeName}&businessNo=${item.businessNo}`,
        animationType: "pop-in",
        animationDuration: 300,
      });
      this.isFromDetail = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.list-content {
  display: flex;
  flex-direction: column;
  height: calc(100vh);
}

.search {
  padding: 0 10px;
  display: flex;
  color: $uni-color-primary;
  justify-content: space-between;
  font-size: 14px;

  align-items: center;

  .search-box {
    flex: 1;
  }
}
</style>
